package net.wanderinghorse.jsonmessage;

import java.io.PrintStream;

/**
 * A Request.post() callback handler which simply sends its arguments
 * to a PrintStream (in JSON format). It is intended only for debugging/testing
 * purposes, and not for "production use."
 */
public class CallbackRequestOptToPrintStream implements CallbackRequestOpt {
    private PrintStream stream;

    /**
     * Sets up this object to use the given stream for output.
     * @param ps The output stream. If it is null then System.out
     * is used.
     */
    public CallbackRequestOptToPrintStream( PrintStream ps ) {
        this.stream = (null!=ps) ? ps : System.out;
    }

    /**
     * Equivalent to CallbackRequestOptToPrintStream(null).
     */
    public CallbackRequestOptToPrintStream() {
        this(null);
    }

    private String handlerName = null;

    /**
     * A name to use for this object, primarily for debugging whether this is, e.g.
     * a beforePost() or afterPost() handler.
     * @param v The name string. May be null.
     * @return This object.
     */
    public CallbackRequestOptToPrintStream setName(String v) {
        this.handlerName = v;
        return this;
    }

    /**
     * Outputs the request and options to the stream passed in to the ctor,
     * in JSON format (but the output itself is not structured like a JSON
     * object, and cannot be used as-is back in as well-formed JSON).
     *
     * If an exception is thrown by r.toJSON() or o.toJSON() then an error
     * message is sent to the output stream.
     *
     * @param r The request which failed.
     * @param o The connection options used for the request.
     */
    public void invoke(Request r, PostOptions o) {
        this.stream.println( getClass().getName()+"processResponse()[name="
                +this.handlerName
                +"]: "
        );
        try {
            int indent = JSONMessage.getDefaultIndentation();
            this.stream.println(
                "Request = "
                +r.toJSON( indent )
                +"\nPostOptions = "+o.toJSON(indent)
            );
        }
        catch( Exception e ) {
            this.stream.println( "Exception processResponse() handler: "+e.toString());
        }
    }
}
